from django.conf import settings
from django.http import Http404
from django.shortcuts import render

# Create your views here.
from django.views.decorators.http import require_POST

from apps.articles.models import Article, ArticleCategory, Comment, Banner
from apps.articles.serializers import ArticleSerializer, CommentSerializer
from apps.ynauth.decorators import yn_login_required
from apps.ynauth.models import User
from .forms import PublishCommentForm
from utils import restful


def index(request):
    count = settings.ONE_PAGE_ARTICLE_COUNT
    # category和author要提前一起查找，不然会发生多次查询
    articles = Article.objects.filter(delete=False).select_related('category', 'author').all()[0:count]
    categories = ArticleCategory.objects.all()
    context = {
        'articles': articles,
        'categories': categories,
        'banners': Banner.objects.all()
    }
    return render(request, 'articles/index.html', context=context)

def article_list(request):
    """
    通过p参数来获取指定页数的数据
    :param request:
    :return:
    """
    page = int(request.GET.get('p', 1))
    start = (page - 1) * settings.ONE_PAGE_ARTICLE_COUNT
    end = start + settings.ONE_PAGE_ARTICLE_COUNT
    category_id = int(request.GET.get('category_id', 0))
    if category_id == 0:
        articles = Article.objects.select_related('category', 'author').all()[start:end]
    else:
        articles = Article.objects.select_related('category', 'author').filter(category__id=category_id)[start:end]
    serializer = ArticleSerializer(articles, many=True)
    data = serializer.data
    return restful.ok(data=data)

def article_detail(request, article_id):
    """
    根据id获取文章详情
    :param request:
    :param article_id:
    :return:
    """
    try:
        article = Article.objects.select_related('category', 'author').\
            prefetch_related("comments__author").\
            prefetch_related("comments__parent").\
            prefetch_related("comments__reply_to").get(pk=article_id)
        context = {
            'article': article
        }
        return render(request, 'articles/article_detail.html', context=context)
    except Article.DoesNotExist:
        raise Http404()

@require_POST
@yn_login_required
def publish_comment(request):
    form = PublishCommentForm(request.POST)
    if form.is_valid():
        article_id = form.cleaned_data.get('article_id')
        content = form.cleaned_data.get('content')
        comment_id = request.POST.get('comment_id')
        reply_user_id = request.POST.get('reply_user_id')
        reply_user = None
        parent = None
        try:
            article = Article.objects.get(pk=article_id)
            if comment_id:
                parent = Comment.objects.get(pk=comment_id)
            if reply_user_id:
                reply_user = User.objects.get(pk=reply_user_id)
        except:
            return restful.params_error(message='没有这条文章或这条评论！')
        comment = Comment.objects.create(content=content, article=article, author=request.user, parent=parent, reply_to=reply_user)
        serializer = CommentSerializer(comment)
        return restful.result(data=serializer.data)
    else:
        return restful.params_error(message=form.get_error())

def search(request):
    return render(request, 'search/search.html')
